import { LCache } from './storage'

type LogLevel = 'info' | 'warn' | 'error'
type Logger = {
  [key in LogLevel]: Fn<void>
}

// @ts-ignore
const { NAIM_LOG_LEVEL: allowLevel = 'info', DEV: isDev = false } =
  // @ts-ignore
  import.meta.env ?? {}

export function createLogger(prefix = 'msg') {
  const logLevels: Array<LogLevel> = ['info', 'warn', 'error']
  const colorMap = {
    debug: 'green',
    info: 'blue',
    warn: 'orange',
    error: 'red',
  }
  const allowIndex = logLevels.findIndex((elevel) => elevel === allowLevel)
  const logger = {} as Logger

  const appConfig = LCache.get('appConfig') || {}

  logLevels.forEach((level) => {
    logger[level] = (...args: any[]) => {
      // 输出日志级别控制
      const index = logLevels.findIndex((elevel) => elevel === level)
      if (index < allowIndex && !appConfig.isDebug) return

      if (
        appConfig.loggerDebugEnable &&
        args.some(
          (arg) =>
            arg &&
            arg.toString().toLowerCase().includes(appConfig.loggerDebugKW),
        )
      ) {
        // eslint-disable-next-line no-debugger
        debugger
      }

      console.log(
        `%c [${(level + ':' + prefix).toUpperCase()}] `,
        `color: ${colorMap[level]}`,
        ...args,
      )
    }
  })
  return logger
}
